package com.ykl.cas.authentication;

import com.ykl.cas.entity.CustomCredential;
import com.ykl.cas.exception.CheckCodeErrorException;
import com.ykl.cas.exception.UserDisabledException;
import com.ykl.cas.utils.DataSourceUtils;
import com.ykl.cas.utils.SecurityUtils;
import org.apereo.cas.authentication.*;
import org.apereo.cas.authentication.handler.support.AbstractPreAndPostProcessingAuthenticationHandler;
import org.apereo.cas.authentication.principal.PrincipalFactory;
import org.apereo.cas.services.ServicesManager;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.security.auth.login.AccountException;
import javax.security.auth.login.FailedLoginException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class CustomerHandlerAuthentication extends AbstractPreAndPostProcessingAuthenticationHandler {

  public CustomerHandlerAuthentication(String name, ServicesManager servicesManager, PrincipalFactory principalFactory, Integer order) {
    super(name, servicesManager, principalFactory, order);
  }

  @Override
  public boolean supports(Credential credential) {
    //判断传递过来的Credential 是否是自己能处理的类型
    return credential instanceof CustomCredential;
  }

  @Override
  protected AuthenticationHandlerExecutionResult doAuthentication(Credential credential) throws GeneralSecurityException, PreventedException {

    CustomCredential customCredential = (CustomCredential) credential;

    String username = customCredential.getUsername();
    String password = customCredential.getPassword();
    String captcha = customCredential.getCapcha();

    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    String right = attributes.getRequest().getSession().getAttribute("captcha_code").toString();
//判断验证码是否正确
    if (!captcha.equalsIgnoreCase(right)) {
      throw new CheckCodeErrorException();
    }
    // 创建JDBC模板
    JdbcTemplate jdbcTemplate = new JdbcTemplate();
    jdbcTemplate.setDataSource(DataSourceUtils.getDataSource());

    String sql = "SELECT * FROM sys_user WHERE user_name = ?";

    CustomCredential info = (CustomCredential) jdbcTemplate.queryForObject(sql, new Object[]{username}, new BeanPropertyRowMapper(CustomCredential.class));
    if (info == null) {
      throw new AccountException("Sorry, username not found!");
    }
    String disabled = info.getStatus();
    if (disabled.equals("1")) {
      throw new UserDisabledException();
    }
    boolean isTruePassword = SecurityUtils.matchesPassword(password, info.getPassword());
    if (!isTruePassword) {
      throw new FailedLoginException("Sorry, password not correct!");
    } else {
      //可自定义返回给客户端的多个属性信息
      HashMap<String, Object> returnInfo = new HashMap<>();
      returnInfo.put("username", username);
      final List<MessageDescriptor> list = new ArrayList<>();
//      return createHandlerResult(customCredential,
//              this.principalFactory.createPrincipal(username, Collections.emptyMap()), list);
      return createHandlerResult(customCredential,
              this.principalFactory.createPrincipal(username, returnInfo), list);
    }
  }
}